package com.zlm.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlm.common.constant.WareConstant;
import com.zlm.common.utils.PageUtils;
import com.zlm.common.utils.Query;
import com.zlm.mall.ware.dao.PurchaseDao;
import com.zlm.mall.ware.entity.PurchaseDetailEntity;
import com.zlm.mall.ware.entity.PurchaseEntity;
import com.zlm.mall.ware.service.PurchaseDetailService;
import com.zlm.mall.ware.service.PurchaseService;
import com.zlm.mall.ware.service.WareSkuService;
import com.zlm.mall.ware.vo.MergeVo;
import com.zlm.mall.ware.vo.PurchaseDoneVo;
import com.zlm.mall.ware.vo.PurchaseItemDoneVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    PurchaseDetailService purchaseDetailService;
    @Resource
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //判断是否有合并单id
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            //新建
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATED.getCode());

            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //确认采购单是0,1才可以合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntityList = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item);
            if (detailEntity.getStatus() == WareConstant.PurchaseDetailEnum.CREATED.getCode() ||
                    detailEntity.getStatus() == WareConstant.PurchaseDetailEnum.ASSIGNED.getCode()) {
                detailEntity.setPurchaseId(finalPurchaseId);
                detailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
                return detailEntity;
            } else {
                log.warn("采购单id为:{}的已领取", mergeVo.getPurchaseId().toString());
                return null;
            }


        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(detailEntityList);

        //更新采购单时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setCreateTime(new Date());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    /**
     * @param ids 采购单id
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {

        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            //确认当前采购单是新建或已分配状态
            if (item.getStatus() == WareConstant.PurchaseEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(purchaseEntity -> {

            purchaseEntity.setStatus(WareConstant.PurchaseEnum.RECEIVE.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).collect(Collectors.toList());

        //改变采购单状态
        this.updateBatchById(collect);

        collect.forEach(purchaseEntity -> {
            //查询出采购项
            List<PurchaseDetailEntity> list = purchaseDetailService.listDetailByPurchaseId(purchaseEntity.getId());
            List<PurchaseDetailEntity> purchaseDetailEntities = list.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            //改变采购项状态
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        });

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        //改变采购项状态
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        ArrayList<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        boolean flag = true;
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailEnum.HASERROR.getCode()) {
                flag = false;
            }else{
                //成功入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());

            }
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());

            detailEntities.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntities);
        //改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseEnum.FINISH.getCode() : WareConstant.PurchaseEnum.HASERROR.getCode());

        this.updateById(purchaseEntity);



    }
}
